package com.dgut.legalservice.dao;

import com.dgut.legalservice.domain.attachment.Attachment;
import com.dgut.legalservice.domain.contract.*;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

@Mapper
public interface IContractDao {
    /**
     * 添加合同等5个
     * @param contract
     * @return
     */
    @Insert("insert into t_contract(name,contractType,attId,createTime,updateTime,createBy,updateBy) " +
            "values (#{name},#{contractType},#{att.id},now(),now(),#{createBy},#{updateBy})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    public int insertContract(Contract contract);

    @Insert("insert into t_contract_steps_ref(contractId,stepId) " +
            "values (#{contractId},#{stepId})")
    public int insertContractStepRef(Integer contractId,Integer stepId);

    @Insert("insert into t_contract_steps(name,seq,createTime,updateTime,createBy,updateBy) " +
            "values (#{name},#{seq},now(),now(),#{createBy},#{updateBy})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    public int insertContractStep(ContractStep contractStep);

    @Insert("insert into t_contract_steps_items_ref(itemId,stepId) " +
            "values (#{itemId},#{stepId})")
    public int insertContractStepItemRef(Integer itemId,Integer stepId);

    @Insert("insert into t_contract_items(attributeName,attributeValue,seq,createTime,updateTime,createBy,updateBy) " +
            "values (#{attributeName},#{attributeValue},#{seq},now(),now(),#{createBy},#{updateBy})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    public int insertContractItem(ContractItem contractItem);

    /**
     * 添加合同定制记录
     *
     * @param contractRecord
     * @return
     */
    @Insert("insert into t_contract_record(contractId,uploadTime,downloadTime,remark,createTime,updateTime,createBy,updateBy) " +
            "values (#{contractId},#{contractRecord.uploadTime},#{contractRecord.downloadTime},#{contractRecord.remark},now(),now(),#{contractRecord.createBy},#{contractRecord.updateBy})")
    public int insertContractRecord(Integer contractId, ContractRecord contractRecord);

    /**
     * 查找合同内容
     * @param contractStepId
     * @return
     */
    @Select("select it.* from t_contract_steps_items_ref sir " +
            "left join t_contract_items it on it.id=sir.itemId " +
            "where sir.stepId=#{contractStepId}")
    //            User
    public List<ContractItem> findContractItems(Integer contractStepId);

    /**
     * 查找合同步骤
     * @param contractId
     * @return
     */
    @Select("select * from t_contract_steps_ref csr " +
            "left join t_contract_steps st on st.id=csr.stepId " +
            "where csr.contractId=#{contractId}")
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractItems",
                    many = @Many(select = "com.dgut.legalservice.dao.IContractDao.findContractItems"),
                    column = "id")
    //            User
    })
    public List<ContractStep> findContractSteps(Integer contractId);

    /**
     * 查找合同定制记录
     * @param contractId
     * @return
     */
    @Select("select * from t_contract_record where contractId=#{contractId}")
    public ContractRecord findContractRecord(Integer contractId);

    /**
     * 查找某个合同 关联步骤\内容\定制记录 多表查询
     * @param id
     * @return
     */
    @Select("select * from t_contract where id=#{id}")
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractSteps",
                    many = @Many(select = "com.dgut.legalservice.dao.IContractDao.findContractSteps"),
                    column = "id"),
            @Result(property = "contractRecord",
                    one = @One(select = "com.dgut.legalservice.dao.IContractDao.findContractRecord"),
                    column = "id"),
            @Result(property = "att",
                    one = @One(select = "com.dgut.legalservice.dao.IAttachmentDao.findAttachmentById"),
                    column = "attId")
//            @Result(property = "createBy",
//                    one = @One(select = "com.dgut.legalservice.dao.IUserDao.findUser**"),
//                    column = "createBy")
//            @Result(property = "updateBy",
//                    one = @One(select = "com.dgut.legalservice.dao.IUserDao.findUser**"),
//                    column = "updateBy")
    })
    public Contract findContractById(Integer id);

    /**
     * 查找所有定制合同 关联合同定制记录 输出列表 ***分页
     * @return
     */
    @Select("select * from t_contract where attId is null")
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractRecord",
                    one = @One(select = "com.dgut.legalservice.dao.IContractDao.findContractRecord"),
                    column = "id"),
    })
    public List<Contract> findCustomContracts();

    /**
     * 查找所有下载合同 关联合同定制记录\附件 输出列表 ***分页
     * @return
     */
    @Select("select * from t_contract where attId is not null")
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractRecord",
                    one = @One(select = "com.dgut.legalservice.dao.IContractDao.findContractRecord"),
                    column = "id"),
            @Result(property = "att",
                    one = @One(select = "com.dgut.legalservice.dao.IAttachmentDao.findAttachmentById"),
                    column = "attId")
    })
    public List<Contract> findDownloadContracts();

    /**
     * 动态查询合同列表
     * Script方式 ContractVo类
     * @param vo
     * @return
     */
    @Select({"<script>",
            "select distinct c.* from t_contract c",
            "left join t_contract_steps_ref csr on c.id=csr.contractId",
            "left join t_contract_steps st on st.id=csr.stepId",
            "left join t_contract_steps_items_ref sir on sir.stepId=st.id",
            "left join t_contract_items it on it.id=sir.itemId",
            "<where>",
            "    and c.attId is null",
            "    <if test='name != null'>and c.name like concat('%',#{name},'%')</if>",
            "    <if test='type != null and type.length()>0'>and contractType like #{type}</if>",
            "    <if test='text != null'>and attributeValue like concat('%',#{text},'%')</if>",
            "</where>",
            "</script>"})
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractRecord",
                    one = @One(select = "com.dgut.legalservice.dao.IContractDao.findContractRecord"),
                    column = "id"),
    })
    public List<Contract> findCustomContractByVo(ContractVo vo);

    @Select({"<script>",
            "select distinct c.* from t_contract c",
            "<where>",
            "    and c.attId is not null",
            "    <if test='name != null'>and c.name like concat('%',#{name},'%')</if>",
            "    <if test='type != null and type.length()>0'>and contractType like #{type}</if>",
            "</where>",
            "</script>"})
    @Results(value = {
            @Result(property = "id", column = "id", id = true),
            @Result(property = "contractRecord",
                    one = @One(select = "com.dgut.legalservice.dao.IContractDao.findContractRecord"),
                    column = "id"),
            @Result(property = "att",
                    one = @One(select = "com.dgut.legalservice.dao.IAttachmentDao.findAttachmentById"),
                    column = "attId")
    })
    public List<Contract> findDownloadContractByVo(ContractVo vo);

    /**
     * 更新合同 以及步骤\内容\定制记录
     *
     * @param contract
     * @return
     */
    @Update("update t_contract set name=#{name},contractType=#{contractType}," +
            "updateTime=now(),updateBy=#{updateBy} where id=#{id}")
    public int updateContract(Contract contract);

    @Update("update t_contract_steps set name=#{name},seq=#{seq}," +
            "updateTime=now(),updateBy=#{updateBy} where id=#{id}")
    public int updateContractStep(ContractStep contractStep);

    @Update("update t_contract_items set attributeName=#{attributeName},attributeValue=#{attributeValue}," +
            "seq=#{seq},type=#{type},updateTime=now(),updateBy=#{updateBy} where id=#{id}")
    public int updateContractItem(ContractItem contractItem);

    @Update("update t_contract_record set remark=#{remark}," +
            "updateTime=now(),updateBy=#{updateBy} where id=#{id}")
    public int updateContractRecord(ContractRecord contractRecord);

    /**
     * 删除合同等5个
     * @param
     */
    @Delete("delete from t_contract where id=#{id}")
    public int deleteContract(Contract contract);

    @Delete("delete from t_contract_steps_ref where contractId=#{contract.id} and stepId=#{contractStep.id}")
    public int deleteContractStepRef(Contract contract,ContractStep contractStep);

    @Delete("delete from t_contract_steps where id=#{id}")
    public int deleteContractStep(ContractStep contractStep);

    @Delete("delete from t_contract_steps_items_ref where itemId=#{contractItem.id} and stepId=#{contractStep.id}")
    public int deleteContractStepItemRef(ContractItem contractItem, ContractStep contractStep);

    @Delete("delete from t_contract_items where id=#{id}")
    public int deleteContractItem(ContractItem contractItem);

    /**
     * 删除合同定制记录
     * @return
     */
    @Delete("delete from t_contract_record where id=#{id}")
    public int deleteContractRecord(ContractRecord contractRecord);

    /**
     * 合同下载/定制次数加一
     * @param id
     * @return
     */
    @Update("update t_contract_record set downloadTimes=downloadTimes+1 where id=#{id}")
    public int addDownloadTimes(Integer id);

    @Update("update t_contract_record set hasShare=#{hasShare} where id=#{id}")
    public int switchShareStatus(ContractRecord contractRecord);


    //    合同审查
    @Insert("insert into t_contract_audit(contractType,attId,pageSize,orderId,createTime,updateTime,createBy,updateBy) " +
            "values (#{contractType},#{attId},#{pageSize},#{orderId},now(),now(),#{createBy},#{updateBy})")
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    public int insertContractAudit(ContractAudit contractAudit);

    @Select("select * from t_contract_audit where id=#{id}")
    public ContractAudit findContractAuditById(Integer id);

    @Update("update t_contract_audit set attId=#{attId},pageSize=#{pageSize}," +
            "updateTime=now(),updateBy=#{updateBy} where id=#{id}")
    public int updateContractAudit(ContractAudit contractAudit);

    @Select("select count(*) from t_contract_audit where orderId=#{orderId}")
    public int findContractAuditCountByOrderId(Integer orderId);

    @Select("select * from t_contract_audit where orderId=#{orderId}")
    public ContractAudit findContractAuditByOrderId(Integer orderId);
}
